package com.sharad.quizbowl.ui.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sharad.quizbowl.ui.dao.dao.TossupsDao;
import com.sharad.quizbowl.ui.dao.dto.Tossups;
import com.sharad.quizbowl.ui.dao.factory.TossupsDaoFactory;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class BrowserServlet extends HttpServlet {
	private static final long serialVersionUID = -4563374109821450259L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		TossupsDao dao = TossupsDaoFactory.create();
		PrintWriter writer = null;
		response.setContentType("text/javascript;charset=utf-8");
		String alt = request.getParameter("alt");
		try {
			writer = response.getWriter();
			try {

				if (request.getParameter("type") != null) {
					writer.print("select " + request.getParameter("type")
							+ " from tossups where "
							+ request.getParameter("type") + " like '"
							+ request.getParameter("value") + "%'");
					Tossups[] s = dao.findByDynamicWhere(request.getParameter("type") + " like '"
							+ request.getParameter("value") + "'", null);

					XStream xstream = null;

					if (alt == null) {
						xstream = new XStream(new DomDriver());
						xstream.setMode(XStream.NO_REFERENCES);
						xstream.alias("tossup", Tossups.class);
						writer.print(xstream.toXML(s));
					} else if (alt.equals("json-in-script")) {
						xstream = new XStream(
								new JsonHierarchicalStreamDriver());
						xstream.setMode(XStream.NO_REFERENCES);
						xstream.alias("tossup", Tossups.class);
						writer.print((request.getParameter("callback") == null ? "callback"
								: request.getParameter("callback"))
								+ "(");
						writer.print(xstream.toXML(s));
						writer.print(")");
					}
				}
			} catch (Throwable e) {
				writer.print("Error: query did not work!\n");
				writer.print(e.getMessage());

			}
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
